package com.gxuwz.endrskyweather;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.gxuwz.endrskyweather.model.Hour1dataItem;
import com.gxuwz.endrskyweather.util.CodeCastText;
import com.gxuwz.endrskyweather.viewmodel.WeatherForecastViewModel;

public class Weather24hFragment extends Fragment {
    private static final String ARG_CITY_NAME = "city_name";
    private static final String ARG_CITY_CODE = "city_code";
    private static final String TAG = "Weather24hFragment";
    private WeatherForecastViewModel viewModel;
    private boolean isObserverRegistered;

    public static Weather24hFragment newInstance(String cityName, String cityCode) {
        Weather24hFragment fragment = new Weather24hFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CITY_NAME, cityName);
        args.putString(ARG_CITY_CODE, cityCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                           @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.weather_24h, container, false);
        viewModel = new ViewModelProvider(requireParentFragment()).get(WeatherForecastViewModel.class);
        isObserverRegistered = false;
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // Get HorizontalScrollView from layout
        HorizontalScrollView scrollView = view.findViewById(R.id.horizontal_scroll_view);
        LinearLayout container = new LinearLayout(requireContext());
        container.setOrientation(LinearLayout.HORIZONTAL);
        scrollView.addView(container);

        // Load 24h forecast data
        // String cityName = getArguments() != null ? getArguments().getString(ARG_CITY_NAME) : "";
         String cityCode = getArguments() != null ? getArguments().getString(ARG_CITY_CODE) : "";
        viewModel.loadHourlyForecast(cityCode);
        
        // Observe hourly forecast data only once
        if (!isObserverRegistered) {
            viewModel.getHourlyForecast().observe(getViewLifecycleOwner(), forecast -> {
                if (forecast != null && !forecast.isEmpty()) {
                    try {
                        // Clear previous views
                        container.removeAllViews();
                        // Create a view for each hourly forecast
                        LayoutInflater inflater = LayoutInflater.from(requireContext());
                        for (Hour1dataItem item : forecast) {
                            View hourlyView = inflater.inflate(R.layout.item_hourly_forecast, container, false);
                            TextView timeView = hourlyView.findViewById(R.id.tv_hourly_forecast_time);
                            ImageView weatherIcon = hourlyView.findViewById(R.id.iv_hourly_forecast_pic);
                            TextView tempView = hourlyView.findViewById(R.id.tv_hourly_forecast_temp);
                            TextView windView = hourlyView.findViewById(R.id.tv_hourly_forecast_wind);
                            TextView windLevelView = hourlyView.findViewById(R.id.tv_hourly_forecast_wind_level);
                            String time = item.getJf().substring(item.getJf().length() - 2);    // 取最后两位为时间，前面的日期舍弃
                            timeView.setText(time + "时");    // 取最后两位为时间，前面的日期舍弃
                            // 根据天气代码设置天气图标
                            if (Integer.parseInt(time) < 6 || Integer.parseInt(time) > 18) {
                                weatherIcon.setImageResource(getResources().getIdentifier("n" + item.getJa(), "drawable", requireContext().getPackageName()));
                            } else {
                                weatherIcon.setImageResource(getResources().getIdentifier("d" + item.getJa(), "drawable", requireContext().getPackageName()));
                            }
                            tempView.setText(item.getJb() + "℃");
                            windView.setText(CodeCastText.WindCast(item.getJd()));
                            windLevelView.setText(CodeCastText.WindPowerCast(item.getJc()));
                            container.addView(hourlyView);
                        }
                    } catch (Exception e) {
                        Toast.makeText(requireContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "Error loading hourly forecast data: ", e);
                    }
                } else {
                    // Show error or empty state
                    Toast.makeText(requireContext(), "无法获取天气预报数据", Toast.LENGTH_SHORT).show();
                }
                viewModel.getHour3ForecastTip().observe(getViewLifecycleOwner(), tip -> {
                    if (tip != null) {
                        try {
                            TextView tipView = view.findViewById(R.id.tv_weather_3h_tip);
                            tipView.setText(tip);
                        } catch (Exception e) {
                            Log.e(TAG, "Error loading 3h forecast tip: ", e);
                        }
                    }
                });
            });
            isObserverRegistered = true;
        }

    }
}
